# encoding: utf-8
import requests
import pandas as pd
from typing import Optional, Union, List
from loguru import logger
from datetime import datetime
from config.settings import settings


class SectorwiseMarketFactorsService:
    """分板块市场整体指标数据服务类"""
    
    def __init__(self):
        """
        初始化服务
        """
        self.api_base_url = f"{settings.data_query_host}/data_query/sectorwise_market_factors"
        
    def get_sectorwise_market_factors(self, 
                                    start_date: str, 
                                    end_date: str,
                                    list_sector: Optional[Union[int, List[int]]] = None) -> Optional[pd.DataFrame]:
        """
        查询分板块市场整体指标数据
        
        Args:
            start_date: 查询开始日期，格式为 YYYY-MM-DD
            end_date: 查询结束日期，格式为 YYYY-MM-DD
            list_sector: 板块代码，可选参数
                        1-主板；2-创业板；3-科创板；4-北交所
                        可传入单个数字或数字列表，不传则查询所有板块
                        
        Returns:
            DataFrame 包含以下字段:
            - date: 日期
            - list_sector: 板块代码
            - total_market_cap: 总市值
            - float_market_cap: 流通市值
            - amount: 成交金额
            如果获取失败返回 None
        """
        try:
            # 构建请求URL - 使用从配置获取的URL
            url = self.api_base_url
            
            # 构建请求参数
            params = {
                "start_date": start_date,
                "end_date": end_date
            }
            
            # 处理list_sector参数
            if list_sector is not None:
                if isinstance(list_sector, int):
                    params["list_sector"] = list_sector
                elif isinstance(list_sector, list):
                    # 如果是列表，转换为逗号分隔的字符串
                    params["list_sector"] = ",".join(map(str, list_sector))
            
            logger.info(f"Requesting sectorwise market factors data: {params}")
            
            # 发送请求
            response = requests.get(
                url,
                params=params,
                timeout=settings.request_timeout_seconds,
            )
            response.raise_for_status()
            
            # 解析响应数据
            data = response.json()
            
            if data and "data" in data:
                df = pd.DataFrame(data["data"])
                
                # 确保日期格式正确
                if "date" in df.columns:
                    df["date"] = pd.to_datetime(df["date"])
                
                # 确保数值列的数据类型正确
                numeric_columns = ["total_market_cap", "float_market_cap", "amount"]
                for col in numeric_columns:
                    if col in df.columns:
                        df[col] = pd.to_numeric(df[col], errors="coerce")
                
                logger.info(f"Successfully retrieved {len(df)} records of sectorwise market factors data")
                return df
            else:
                logger.warning("No data returned from API")
                return None
                
        except requests.exceptions.RequestException as e:
            logger.error(f"HTTP request failed: {e}")
            return None
        except Exception as e:
            logger.error(f"Failed to get sectorwise market factors data: {e}")
            return None
    
    def get_sector_name(self, sector_code: int) -> str:
        """
        获取板块名称
        
        Args:
            sector_code: 板块代码
            
        Returns:
            板块名称
        """
        sector_names = {
            1: "主板",
            2: "创业板", 
            3: "科创板",
            4: "北交所"
        }
        return sector_names.get(sector_code, f"未知板块({sector_code})")
    
    def get_formatted_data(self, 
                          start_date: str, 
                          end_date: str,
                          list_sector: Optional[Union[int, List[int]]] = None) -> Optional[pd.DataFrame]:
        """
        获取格式化后的分板块市场指标数据（用于显示）
        
        Args:
            start_date: 查询开始日期，格式为 YYYY-MM-DD
            end_date: 查询结束日期，格式为 YYYY-MM-DD
            list_sector: 板块代码，可选参数
                        
        Returns:
            格式化后的DataFrame，包含板块名称等便于阅读的信息
        """
        df = self.get_sectorwise_market_factors(start_date, end_date, list_sector)
        
        if df is None or df.empty:
            return None
            
        # 添加板块名称列
        df["sector_name"] = df["list_sector"].apply(self.get_sector_name)
        
        # 格式化数值列（转换为亿元）
        if "total_market_cap" in df.columns:
            df["total_market_cap_yi"] = (df["total_market_cap"] / 1e8).round(2)
            
        if "float_market_cap" in df.columns:
            df["float_market_cap_yi"] = (df["float_market_cap"] / 1e8).round(2)
            
        if "amount" in df.columns:
            df["amount_yi"] = (df["amount"] / 1e8).round(2)
        
        # 重新排列列顺序，便于查看
        columns_order = ["date", "list_sector", "sector_name"]
        if "total_market_cap_yi" in df.columns:
            columns_order.append("total_market_cap_yi")
        if "float_market_cap_yi" in df.columns:
            columns_order.append("float_market_cap_yi")
        if "amount_yi" in df.columns:
            columns_order.append("amount_yi")
            
        # 保留原始列
        remaining_cols = [col for col in df.columns if col not in columns_order]
        columns_order.extend(remaining_cols)
        
        df = df[columns_order]
        
        return df
